package com.bayss.core.service.found;

import com.bayss.core.entity.found.ZaihuMessage;
import com.bayss.core.entity.found.ZaihuMessageLike;
import com.bayss.core.entity.found.ZaihuMessageLikeExample;
import com.bayss.core.entity.found.mapper.ZaihuMessageLikeMapper;
import com.bayss.core.entity.found.mapper.ZaihuMessageMapper;
import com.bayss.core.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageLikeService {

    @Autowired
    private ZaihuMessageLikeMapper zaihuMessageLikeMapper;
    @Autowired
    private ZaihuMessageMapper zaihuMessageMapper;

    /**
     * 根据留言id查询点赞列表
     * @param messageId
     * @param userId
     * @return
     */
    public ZaihuMessageLike addMessageLikeByMessageId(Integer messageId, Integer userId) {
        ZaihuMessageLikeExample example = new ZaihuMessageLikeExample();
        example.createCriteria().andMessageIdEqualTo(messageId).andUserIdEqualTo(userId);
        List<ZaihuMessageLike> zaihuMessageLikes = zaihuMessageLikeMapper.selectByExample(example);
        ZaihuMessageLike zaihuMessageLike = null;
        if (CollectionUtils.isNotEmpty(zaihuMessageLikes)) {
            zaihuMessageLike = zaihuMessageLikes.get(0);
        }
        if (zaihuMessageLike == null) {
            ZaihuMessageLike _ZaihuMessageLike = new ZaihuMessageLike();
            _ZaihuMessageLike.setCreateTime(new Date());
            _ZaihuMessageLike.setMessageId(messageId);
            _ZaihuMessageLike.setUserId(userId);
            zaihuMessageLikeMapper.insertSelective(_ZaihuMessageLike);

            ZaihuMessage zaihuMessage = zaihuMessageMapper.selectByPrimaryKey(messageId);
            zaihuMessageMapper.updatelikeNumCream1(zaihuMessage.getId());

        } else {
            zaihuMessageLikeMapper.deleteByExample(example);
            ZaihuMessage zaihuMessage = zaihuMessageMapper.selectByPrimaryKey(messageId);
            if (zaihuMessage != null) {
                Integer messageLikeNum = zaihuMessage.getLikeNum();
                zaihuMessage.setLikeNum(messageLikeNum - 1);
                zaihuMessageMapper.updateByPrimaryKeySelective(zaihuMessage);
            }
        }
        return zaihuMessageLike;
    }
}
